package io.gitee.dtdage.app.boot.starter.data.redis;

import io.gitee.dtdage.app.boot.starter.data.redis.context.KeyExpireHandlerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * @author WFT
 * @since 2024/4/14
 */
@Configuration
@ComponentScan
public class RedisAutoConfiguration {

    /**
     * @noinspection SpringJavaInjectionPointsAutowiringInspection
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        return template;
    }

    /**
     * @noinspection SpringJavaInjectionPointsAutowiringInspection
     */
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        return container;
    }

    @Bean
    public KeyExpirationEventMessageListener keyExpirationEventMessageListener(RedisMessageListenerContainer container, KeyExpireHandlerFactory factory) {
        return new KeyExpirationEventMessageListener(container) {
            @Override
            public void onMessage(Message message, byte[] pattern) {
                //  得到Key数组
                String[] keys = new String(message.getBody()).split(":");
                //  调用事件处理器
                factory.getOptional(keys[0]).ifPresent(handler -> handler.onApplicationEvent(keys));
            }
        };
    }

}
